// 基本Express服务器设置
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
const PORT = 3000;

// 启用CORS以允许前端访问
app.use(cors({
  origin: '*', // 允许所有来源访问API
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// 解析请求数据
app.use(express.json({ limit: '50mb' })); // 增加请求体大小限制
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// 为静态文件提供服务
app.use(express.static(path.join(__dirname, '../frontend')));

// 创建简单的授权中间件
const authMiddleware = (req, res, next) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    // 检查是否在模拟模式下
    if (req.query.mockMode === 'true') {
      console.log('模拟授权模式 - 跳过验证');
      return next();
    }
    return res.status(401).json({ 
      success: false, 
      message: '未授权的访问' 
    });
  }
  
  // 在实际应用中，这里应该验证token
  const token = authHeader.split(' ')[1];
  // 简单的token验证，真实应用应使用JWT或其他方式验证
  if (token.startsWith('mock-token-')) {
    next();
  } else {
    res.status(401).json({ 
      success: false, 
      message: '无效的令牌' 
    });
  }
};

// 游戏API路由
app.get('/api/games', (req, res) => {
  console.log('收到获取游戏列表请求');
  
  // 添加分页支持
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const category = req.query.category;
  
  // 模拟的游戏数据
  let games = [
    { id: 1, title: '冒险游戏1', category: 'adventure', thumbnail: '/images/adventure-games.jpg', plays: 1250, rating: 4.5 },
    { id: 2, title: '动作游戏1', category: 'action', thumbnail: '/images/action-games.jpg', plays: 3580, rating: 4.2 },
    { id: 3, title: '益智游戏1', category: 'puzzle', thumbnail: '/images/puzzle-games.jpg', plays: 2150, rating: 4.8 },
    { id: 4, title: '冒险游戏2', category: 'adventure', thumbnail: '/images/adventure-games.jpg', plays: 1050, rating: 4.1 },
    { id: 5, title: '动作游戏2', category: 'action', thumbnail: '/images/action-games.jpg', plays: 2870, rating: 4.4 },
    { id: 6, title: '益智游戏2', category: 'puzzle', thumbnail: '/images/puzzle-games.jpg', plays: 1850, rating: 4.6 }
  ];
  
  // 应用类别过滤
  if (category) {
    games = games.filter(game => game.category === category);
  }
  
  // 应用分页
  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;
  const paginatedGames = games.slice(startIndex, endIndex);
  
  res.json({
    success: true,
    message: '游戏列表获取成功',
    games: paginatedGames,
    pagination: {
      total: games.length,
      page,
      limit,
      pages: Math.ceil(games.length / limit)
    }
  });
});

// 获取游戏详情API
app.get('/api/games/:id', (req, res) => {
  const gameId = parseInt(req.params.id);
  console.log(`收到获取游戏详情请求, ID: ${gameId}`);
  
  // 模拟游戏数据
  const game = {
    id: gameId,
    title: `游戏${gameId}`,
    category: gameId % 3 === 0 ? 'puzzle' : (gameId % 2 === 0 ? 'action' : 'adventure'),
    thumbnail: `/images/${gameId % 3 === 0 ? 'puzzle' : (gameId % 2 === 0 ? 'action' : 'adventure')}-games.jpg`,
    description: `这是游戏${gameId}的详细描述，包含了游戏的玩法和特色。`,
    plays: Math.floor(Math.random() * 5000) + 1000,
    rating: (Math.random() * 2 + 3).toFixed(1),
    creator: {
      id: 1,
      username: '创作者',
      avatar: '/images/avatar.jpg'
    },
    createdAt: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString()
  };
  
  res.json({
    success: true,
    game
  });
});

// 上传游戏API
app.post('/api/games/upload', (req, res) => {
  // 这里只是模拟上传，实际应用中需要处理文件上传
  const { title, description, category } = req.body;
  
  console.log('收到游戏上传请求:', { title, description, category });
  
  // 模拟处理延迟
  setTimeout(() => {
    const gameId = Math.floor(Math.random() * 1000) + 1;
    const filePath = `/uploads/games/game_${gameId}.zip`;
    const thumbnailPath = `/uploads/thumbnails/thumb_${gameId}.jpg`;
    
    // 返回成功响应
    res.json({
      success: true,
      message: '游戏上传成功，等待审核',
      gameId: gameId,
      gamePath: filePath,
      thumbnailPath: thumbnailPath,
      game: {
        id: gameId,
        title: title || `新游戏${gameId}`,
        category: category || 'adventure',
        description: description || '这是一个新上传的游戏',
        filePath: filePath,
        thumbnail: thumbnailPath,
        status: 'pending',
        plays: 0,
        downloads: 0,
        rating: 0,
        createdAt: new Date().toISOString()
      }
    });
  }, 1500); // 模拟上传延迟
});

// 用户API路由
app.post('/api/auth/login', (req, res) => {
  const { username, password } = req.body;
  
  console.log('收到登录请求:', { username });
  
  // 简单的登录验证
  if (username && password) {
    const token = 'mock-token-' + Date.now();
    
    // 返回成功响应
    res.json({
      success: true,
      message: '登录成功',
      user: {
        id: 1,
        username,
        email: `${username}@example.com`,
        avatar: '/images/avatar.jpg',
        createdAt: new Date().toISOString()
      },
      token: token
    });
  } else {
    res.status(400).json({
      success: false,
      message: '用户名或密码错误'
    });
  }
});

// 获取用户上传的游戏
app.get('/api/users/me/games', authMiddleware, (req, res) => {
  console.log('收到获取用户游戏请求');
  
  // 模拟用户上传的游戏
  const userGames = [
    {
      id: 101,
      title: '我的游戏1',
      category: 'action',
      thumbnail: '/images/action-games.jpg',
      status: 'approved',
      plays: 245,
      rating: 4.3,
      createdAt: new Date(Date.now() - 5000000000).toISOString()
    },
    {
      id: 102,
      title: '我的游戏2',
      category: 'puzzle',
      thumbnail: '/images/puzzle-games.jpg',
      status: 'pending',
      plays: 0,
      rating: 0,
      createdAt: new Date(Date.now() - 2000000000).toISOString()
    }
  ];
  
  res.json({
    success: true,
    games: userGames
  });
});

// 热门游戏API
app.get('/api/games/hot', (req, res) => {
  const limit = parseInt(req.query.limit) || 5;
  
  console.log(`收到获取热门游戏请求, 限制: ${limit}`);
  
  // 模拟热门游戏
  const hotGames = [
    { id: 5, title: '热门游戏1', category: 'action', thumbnail: '/images/action-games.jpg', plays: 8750, rating: 4.9 },
    { id: 8, title: '热门游戏2', category: 'adventure', thumbnail: '/images/adventure-games.jpg', plays: 7650, rating: 4.8 },
    { id: 12, title: '热门游戏3', category: 'puzzle', thumbnail: '/images/puzzle-games.jpg', plays: 6950, rating: 4.7 },
    { id: 15, title: '热门游戏4', category: 'action', thumbnail: '/images/action-games.jpg', plays: 6350, rating: 4.6 },
    { id: 18, title: '热门游戏5', category: 'adventure', thumbnail: '/images/adventure-games.jpg', plays: 5850, rating: 4.5 },
  ].slice(0, limit);
  
  res.json({
    success: true,
    games: hotGames
  });
});

// 主页路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/index.html'));
});

// 404处理
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: '请求的资源不存在'
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    success: false,
    message: '服务器内部错误'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`===========================================`);
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`API端点可以通过 http://localhost:${PORT}/api 访问`);
  console.log(`===========================================`);
}); 